﻿using Future.Common.Exception;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Future.Web.Filter
{
    /// <summary>
    /// 异常过滤器
    /// </summary>
    [AttributeUsage(AttributeTargets.All)]
    public class CustomExceptionFilterAttribute : Attribute, IExceptionFilter
    {
        private readonly ILogger<CustomExceptionFilterAttribute> _logger;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="logger"></param>
        public CustomExceptionFilterAttribute(ILogger<CustomExceptionFilterAttribute> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {

            if (context.ExceptionHandled == false)
            {
                string url = context.HttpContext.Request.Path.Value ?? string.Empty;
                string actionName = context.ActionDescriptor.DisplayName ?? string.Empty;
                if (context.Exception is ExpireException)
                {
                    context.Result = new JsonResult(ResultVo.Expire(msg: context.Exception.Message));
                }
                else if (context.Exception is BusinessException)
                {
                    context.Result = new JsonResult(ResultVo.Fail(context.Exception.Message));
                }
                else
                {
                    context.Result = new JsonResult(ResultVo.Fail("系统异常请联系管理员！"));
                    _logger.LogError(context.Exception, $"{url}----->actionName={actionName} \n Message={context.Exception}");
                }
                _logger.LogInformation($"{url}----->actionName={actionName} \n Message={context.Exception.Message}");
            }
            context.ExceptionHandled = true;
        }
    }
}
